import json

from django.core import serializers
from django.core.serializers.json import DjangoJSONEncoder
from django.http import JsonResponse
from django.shortcuts import render

from msi.models import Book


# Create your views here.


def index(request):
    books = Book.objects.all()
    # print(json.dumps(books))
    books = serializers.serialize("python", books)
    books = {
        "books_view": json.dumps(books, cls=DjangoJSONEncoder),
        "books": Book.objects.all()
    }
    print(books)
    return render(request, 'index.html', books)


def read_json(request):
    goods = Book.objects.all()
    json_data = json.loads(serializers.serialize('json', goods, ensure_ascii=False))
    print(json_data)
    print(type(json_data))
    return JsonResponse({
        'code': '0000',
        'data': json_data,
        'msg': '获取文章列表成功'
    })


def write_json(request):
    print(request)
    data = json.loads(request.body)

    print(data)
    return JsonResponse({
        'code': '0000',
        'msg': '获取文章列表成功'
    })
